package com.francis.demo.aspect;

import com.francis.spring.framework.aop.aspect.FrancisJoinPoint;
import com.francis.spring.framework.aop.intercept.FrancisMethodInvocation;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInvocation;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.Arrays;

/**
 * @Author Francis
 * @Date 2020/11/22 23:13
 * @Version 1.0
 * @Description:
 */
@Slf4j
public class LogAspect {


    //在调用一个方法之前，执行before方法
    public void before(FrancisJoinPoint joinPoint){
        joinPoint.setUserAttribute("startTime_" + joinPoint.getMethod().getName(),System.currentTimeMillis());
        //这个方法中的逻辑，是由我们自己写的
        log.info("Invoker Before Method!!!" +
                "\nTargetObject:" +  joinPoint.getThis() +
                "\nArgs:" + Arrays.toString(joinPoint.getArguments()));
    }

    //在调用一个方法之后，执行after方法
    public void after(FrancisJoinPoint joinPoint){
        log.info("Invoker After Method!!!" +
                "\nTargetObject:" +  joinPoint.getThis() +
                "\nArgs:" + Arrays.toString(joinPoint.getArguments()));
        long startTime = (Long) joinPoint.getUserAttribute("startTime_" + joinPoint.getMethod().getName());
        long endTime = System.currentTimeMillis();
        System.out.println("use time :" + (endTime - startTime));
    }

    public void afterThrowing(FrancisJoinPoint joinPoint, Throwable ex){
        log.info("出现异常" +
                "\nTargetObject:" +  joinPoint.getThis() +
                "\nArgs:" + Arrays.toString(joinPoint.getArguments()) +
                "\nThrows:" + ex.getMessage());
    }


    public Object around(ProceedingJoinPoint  joinPoint){
        Object proceed = null;
        try {
            log.info("around前置通知");
            proceed = joinPoint.proceed();
            System.out.println("后置");
        } catch (Throwable throwable) {
            System.out.println("异常");
            throwable.printStackTrace();
        }finally {
            System.out.println("最终");
        }
        return proceed;
    }
}
